<template>
  <div class="wrap">
    <div class="wrap-button">
      <a-button style="margin-right: 8px" type="primary" @click="showAddUser">新增</a-button>
      <div style="float: right">
        <a-input
          v-model:value="keyword"
          style="width: 180px; margin-right: 8px"
          placeholder="输入关键字查询"
          allow-clear
        >
          <template #prefix>
            <SearchOutlined style="color: #666" />
          </template>
        </a-input>
        <a-button type="primary" @click="handleSearch">查询</a-button>
      </div>
    </div>
    <div class="wrap-table">
      <!-- <BaseTitle title="用户列表" /> -->
      <a-table
        :loading="loading"
        :dataSource="data"
        :columns="columns"
        :pagination="pagination"
        size="middle"
        @change="handleTableChange"
        width="300"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'isLock'">
            <a-tag v-if="record.isLock === '0'" color="cyan">正常</a-tag>
            <a-tag v-else color="red">锁定</a-tag>
          </template>
          <template v-if="column.key === 'operation'">
            <!-- <a-button class="button-interval" type="link" :icon="h(FileTextOutlined)" size="small">
              查看
            </a-button> -->
            <a-button
              class="button-interval"
              type="link"
              :icon="h(SettingOutlined)"
              size="small"
              @click="handleSetting(record)"
            >
              角色
            </a-button>
            <a-button
              class="button-interval"
              type="link"
              :icon="h(DeleteOutlined)"
              size="small"
              @click="handleDeleteUser(record)"
            >
              删除
            </a-button>
          </template>
        </template>
      </a-table>
      <a-modal v-model:visible="open" title="新增用户" @ok="handleAddSubmit">
        <a-form
          ref="formRef"
          style="margin-top: 24px"
          :model="formState"
          name="basic"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
        >
          <a-form-item
            label="用户名"
            name="userName"
            :rules="[{ required: true, message: 'Please input your username!' }]"
          >
            <a-input
              readOnly
              onfocus="this.removeAttribute('readonly');"
              onblur="this.setAttribute('readonly',true);"
              v-model:value="formState.userName"
            />
          </a-form-item>
          <a-form-item
            label="姓名"
            name="realName"
            :rules="[{ required: true, message: 'Please input your realName!' }]"
          >
            <a-input v-model:value="formState.realName" />
          </a-form-item>

          <a-form-item
            label="密码"
            name="password"
            :rules="[{ required: true, message: 'Please input your password!' }]"
          >
            <a-input-password
              readOnly
              onfocus="this.removeAttribute('readonly');"
              onblur="this.setAttribute('readonly',true);"
              v-model:value="formState.password"
            />
          </a-form-item>
          <a-form-item
            label="确认密码"
            name="verifyPassword"
            :rules="[{ required: true, message: 'Please input your verifyPassword!' }]"
          >
            <a-input-password v-model:value="formState.verifyPassword" />
          </a-form-item>

          <a-form-item label="邮箱" name="email">
            <a-input v-model:value="formState.email" />
          </a-form-item>

          <a-form-item
            label="联系方式"
            name="userTel"
            :rules="[
              {
                pattern: /^1[3|5|7|8|9]\d{9}$/,
                message: '请输入正确的号码格式',
                trigger: 'change',
              },
            ]"
          >
            <a-input v-model:value="formState.userTel" />
          </a-form-item>

          <a-form-item label="所属租户" name="tenant">
            <a-select ref="select" v-model:value="formState.tenantId">
              <a-select-option v-for="item in tenants" :key="item.id" :value="item.id">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>

      <a-modal v-model:visible="openRole" title="设置角色" @ok="handleSaveRole" okText="保存">
        <a-table
          rowKey="id"
          :row-selection="{
            selectedRowKeys: state.selectedRowKeys,
            onChange: onSelectChange,
          }"
          :columns="roleColumns"
          :data-source="roleData"
          :pagination="false"
        />
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { h, ref, unref, computed, onMounted, reactive } from 'vue'
  import { DeleteOutlined, SettingOutlined, SearchOutlined } from '@ant-design/icons-vue'
  import { FormInstance, message } from 'ant-design-vue'
  // import { BaseTitle } from '/@/components/Title'

  import { GetUserListModel, FormState } from '/@/api/sys/model/userModel'
  import { RoleInfo, UserRoleModel } from '/@/api/sys/model/roleModel'
  import { TenantModel } from '/@/api/sys/model/tenantModel'
  import { listTenant } from '/@/api/sys/tenant'
  import { getUserList, addUser, deleteUser, listUserRole, saveUserRole } from '/@/api/sys/user'
  import { listRole } from '/@/api/sys/role'
  import { Modal } from 'ant-design-vue'

  const open = ref<boolean>(false)
  const openRole = ref<boolean>(false)
  const settingUserId = ref<string>('')
  const loading = ref(false)
  const roleLoading = ref(false)
  const keyword = ref<string>('')
  const columns = [
    {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName',
      align: 'center',
    },
    {
      title: '姓名',
      dataIndex: 'realName',
      key: 'realName',
      align: 'center',
      width: 140,
      // customCell: (text) => (text ? (text == '周沈斌' ? '我变变变' : text) : '--'),
    },
    {
      title: '所属租户',
      dataIndex: 'tenantName',
      key: 'tenantName',
      align: 'center',
      width: 180,
    },
    {
      title: '联系方式',
      dataIndex: 'userTel',
      key: 'userTel',
      align: 'center',
      width: 180,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      align: 'center',
      width: 280,
      ellipsis: true,
    },
    {
      title: '最近登录ip',
      dataIndex: 'lastLoginIp',
      key: 'lastLoginIp',
      align: 'center',
      width: 180,
    },
    {
      title: '最近登录时间',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      align: 'center',
      width: 150,
    },
    {
      title: '锁定状态',
      dataIndex: 'isLock',
      key: 'isLock',
      align: 'center',
      minWidth: 80,
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      align: 'center',
      width: 165,
    },
  ]
  let data = ref<GetUserListModel[]>([])
  let tenants = ref<TenantModel[]>([])
  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
    size: '',
    showSizeChanger: false,
    showQuickJumper: false,
  })

  const pageParam = computed(() => ({
    query: {
      keyword: unref<string>(keyword),
    },
    current: pagination.value?.current,
    size: pagination.value?.pageSize,
  }))

  const userRoleParam = computed<UserRoleModel>(() => ({
    userId: unref(settingUserId),
    roleIds: state.selectedRowKeys,
  }))

  //#endregion

  const state = reactive<{
    selectedRowKeys: string[]
    loading: boolean
  }>({
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
  })
  const roleColumns = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
    },
    {
      title: '角色编码',
      dataIndex: 'roleCode',
    },
  ]
  const roleData = ref<RoleInfo[]>([])

  onMounted(() => {
    list()
  })

  const handleSearch = () => {
    list()
  }

  async function list() {
    loading.value = true
    const res = await getUserList(unref(pageParam))
    data.value = res.records
    pagination.value.total = Number(res.total)
    pagination.value.current = Number(res.current)
    loading.value = false
  }

  function handleTableChange(page) {
    pagination.value.current = page.current
    list()
  }

  //#region 用户

  const formRef = ref<FormInstance>()

  let formState = reactive<FormState>({
    userName: '',
    password: '',
    realName: '',
    verifyPassword: '',
    email: '',
    userTel: '',
    tenantId: '',
  })

  async function showAddUser() {
    tenants.value = await listTenant()
    open.value = true
    formRef.value?.resetFields()
  }

  const handleAddSubmit = () => {
    formRef.value
      ?.validateFields()
      .then(() => {
        if (formState.password !== formState.verifyPassword) {
          message.error('两次密码不一致')
          return
        }
        console.log('formState', formState)
        addUser(formState).then(() => {
          message.success('添加成功')
          open.value = false
          list()
        })
      })
      .catch(() => {
        message.error('表单填写错误')
      })
  }

  const handleDeleteUser = (record: any) => {
    Modal.confirm({
      title: '提示',
      maskClosable: true,
      content: '确定要删除该用户吗？',
      onOk() {
        deleteUser(record.id).then(() => {
          list()
          message.success('删除成功')
        })
      },
      onCancel() {},
    })
  }

  const handleSetting = (record: any) => {
    state.selectedRowKeys = []
    settingUserId.value = record.id
    openRole.value = true
    roleLoading.value = true
    listRole()
      .then((res) => {
        roleData.value = res
      })
      .then(() => {
        listUserRole(record.id).then((res) => {
          state.selectedRowKeys = res.map((obj) => {
            return obj.id
          })
        })
      })
      .finally(() => {
        roleLoading.value = false
      })
  }

  const handleSaveRole = () => {
    saveUserRole(unref(userRoleParam)).then(() => {
      message.success('保存成功')
      openRole.value = false
    })
  }

  const onSelectChange = (selectedRowKeys: string[]) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys)
    state.selectedRowKeys = selectedRowKeys
  }

  //#endregion
</script>

<style lang="scss" scoped>
  .wrap {
    &-table {
      margin-top: 16px;
    }
  }
</style>
